package com.ysm.smfu.map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.ysm.smfu.R;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.UIUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:Utils <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:   TODO ADD REASON. <br/>
 * Date:     2015年4月7日 下午3:43:05 <br/>
 *
 * @author yiyi.qi
 * @see
 * @since JDK 1.6
 */
public class FoodMapUtils {

    private static ArrayList<Marker> markers = new ArrayList<Marker>();


    /**
     * 添加marker
     */
    public static void addEmulateData(AMap amap, LatLng center, List<PositionEntity> latLngs) {
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
                .fromResource(R.drawable.foodmap_location);
        int count;
        if (latLngs == null)
            count = 1;
        else
            count = 20;
        for (int i = 0; i < count; i++) {
            double latitudeDelt = (Math.random() - 0.5) * 0.1;
            double longtitudeDelt = (Math.random() - 0.5) * 0.1;
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.anchor(0.5f, 0.5f)
                    .icon(bitmapDescriptor)
                    .title("标题:" + i)
                    .position(new LatLng(center.latitude + latitudeDelt, center.longitude + longtitudeDelt));
            Marker marker = amap.addMarker(markerOptions);
            markers.add(marker);
            if (count == 1) {
                // 设置所有maker显示在当前可视区域地图中
                LatLngBounds bounds = new LatLngBounds.Builder()
                        .include(center)
                        .include(new LatLng(center.latitude + latitudeDelt, center.longitude + longtitudeDelt))
                        .build();
                amap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));
            }
        }
    }

    /**
     * 添加marker
     */
    public static void addSignalEmulateData(AMap amap, LatLng latLng) {
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
                .fromResource(R.drawable.foodmap_location);

        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.anchor(0.5f, 0.5f)
                .icon(bitmapDescriptor)
                .title("牛肉面")
                .position(latLng);
        Marker marker = amap.addMarker(markerOptions);
        markers.add(marker);

    }

    /**
     * 移除marker
     */
    public static void removeMarkers() {
        for (Marker marker : markers) {
            marker.remove();
            marker.destroy();
        }
        markers.clear();
    }

    /**
     * 打开地图
     *
     * @param desLoc 目的地
     * @param name   目的地名称
     */
    public static void startMap(Activity activity, LatLng desLoc, String name) {
//            startMap(Uri.parse("geo:" + myLoc.latitude + "," + myLoc.longitude + "?q=" + name));//打开所有注册了geo-uri的应用,但是无法知道选取的是哪一个地图，不能进行坐标转换
        showPopuWindowAndSelectMap(activity, desLoc.longitude, desLoc.latitude);
    }

    public static void startMap(Uri uri) {
        Intent mIntent = new Intent(Intent.ACTION_VIEW, uri);
        UIUtils.startActivity(mIntent);
    }

    public static boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    public static void showPopuWindowAndSelectMap(Activity activity, double desLon, double desLat) {
        PrintUtil.printRespones("经度:" + desLon + "--维度:" + desLat);
        if (isInstallByread("com.autonavi.minimap") && isInstallByread("com.baidu.BaiduMap"))
            showPopuWindowByInstalledMap(0, desLon, desLat, activity);
        else if (!isInstallByread("com.autonavi.minimap") && isInstallByread("com.baidu.BaiduMap"))
            showPopuWindowByInstalledMap(1, desLon, desLat, activity);
        else if (isInstallByread("com.autonavi.minimap") && !isInstallByread("com.baidu.BaiduMap"))
            showPopuWindowByInstalledMap(2, desLon, desLat, activity);
        else if (!isInstallByread("com.autonavi.minimap") && !isInstallByread("com.baidu.BaiduMap"))
            showPopuWindowByInstalledMap(3, desLon, desLat, activity);
    }

    public static void showPopuWindowByInstalledMap(double i, final double desLon, final double desLat,
                                                    final Activity activity) {
        View view = LayoutInflater.from(activity).inflate(R.layout.popupwindow_map, null);
        TextView gdMap = (TextView) view.findViewById(R.id.gdMap);
        TextView bdMap = (TextView) view.findViewById(R.id.bdMap);
        if (i == 1) {
            startBdMap(activity, desLon, desLat);
            return;
        } else if (i == 2) {
            startGdMap(activity, desLon, desLat);
            return;
        } else if (i == 3) {
//            打开web地图
            startMap(Uri.parse("http://uri.amap.com/navigation?from=116.478346,39.997361,startpoint&to=116.3246,39.966577,endpoint" +
                    "&via=116.402796,39.936915,midwaypoint&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0"));
            return;
        }
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
//        popupWindow.setAnimationStyle();//淡显淡出样式
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                removeShade(activity);
            }
        });
        addShade(activity);
//        高德地图
        gdMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startGdMap(activity, desLon, desLat);
                popupWindow.dismiss();
            }
        });
//        百度地图
        bdMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startBdMap(activity, desLon, desLat);
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 添加遮罩
     *
     * @param activity
     */
    private static void addShade(Activity activity) {
        setWindowAlpha(activity, 0.5f);
    }

    private static void removeShade(Activity activity) {
        setWindowAlpha(activity, 1f);
    }

    private static void setWindowAlpha(Activity activity, float alpha) {
        WindowManager.LayoutParams attributes = activity.getWindow().getAttributes();
        attributes.alpha = alpha;
        activity.getWindow().setAttributes(attributes);
    }

    /**
     * 打开百度地图
     *
     * @param activity
     * @param desLon
     * @param desLat
     */
    private static void startBdMap(Activity activity, double desLon, double desLat) {
        double[] desLatLon = gdMapLocToBdMapLoc(desLon, desLat);
        PrintUtil.printRespones("转后坐标:" + desLatLon[0] + "=" + desLatLon[1]);
        Intent intent = new Intent();
        Uri uri = Uri.parse("baidumap://map/direction?destination=" + desLatLon[1] + "," + desLatLon[0] + "&mode=transit&sy=3&index=0&target=1");
        intent.setData(uri);
        activity.startActivity(intent); // 启动调用
    }

    /**
     * 打开高德地图
     *
     * @param activity
     * @param desLon
     * @param desLat
     */
    private static void startGdMap(Activity activity, double desLon, double desLat) {
        Uri uri = Uri.parse("androidamap://route?sourceApplication=云数贸" + "&dlat=" + desLat//终点的纬度
                + "&dlon=" + desLon//终点的经度
                + "&dev=0" + "&t=1");
        Intent intent = new Intent("android.intent.action.VIEW", uri);
        activity.startActivity(intent);
    }

    public static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    /**
     * 高德地图坐标转百度地图坐标
     */
    private static double[] gdMapLocToBdMapLoc(double lon, double lat) {
        double x = lat, y = lon;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double tempLon = z * Math.cos(theta) + 0.0065;
        double tempLat = z * Math.sin(theta) + 0.006;
        double[] gps = {tempLat, tempLon};
        return gps;
    }
}
  
